package be.phl.obstacleapp;

import java.util.ArrayList;
import java.util.List;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.Typeface;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.DragShadowBuilder;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import be.phl.model.DBAdapterScreening;
import wei.mark.standout.StandOutWindow;
import be.phl.webservice.RoomType;

public class ScreeningActivity extends FragmentActivity {
	/**
	 * TODO: CLEAN UP CODE!!!
	 * 
	 * Crashes after a lot of rooms are added
	 * overzicht over alle geselecteerde item
	 * 
	 */

	private static final String TAG = "ScreeningActivity";

	private CustomRoomButton btnTag;

	private LinearLayout viewLinksScrol, knopholder1, knopholder2, knopholder3,
			knopholder4;
	private RelativeLayout viewRechts, knopcontainer, delete;

	private int width, height, ScreeningId, buttonWidth, buttonHeight;
	static int buttonCount = 1;
	static int FloorNr = 0;
	static int counter = 0;

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	MyDragEventListener myDragEventListener = new MyDragEventListener();

	ArrayList<CustomRoomButton> screeningRooms = new ArrayList<CustomRoomButton>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_screening);
		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);

		getScreenDimensions();
		ScreeningId = getIntent().getIntExtra("ScreeningId", 0);
		buttonWidth = getWidth() * 12 / 100;
		buttonHeight = getWidth() * 10 / 100;

		Typeface tf = Typeface.createFromAsset(getAssets(), "com.ttf");

		viewLinksScrol = (LinearLayout) findViewById(R.id.linksinscroll);
		viewRechts = (RelativeLayout) findViewById(R.id.rechts);
		delete = (RelativeLayout) findViewById(R.id.delete);
		knopholder1 = (LinearLayout) findViewById(R.id.knop1);
		knopholder2 = (LinearLayout) findViewById(R.id.knop2);
		knopholder3 = (LinearLayout) findViewById(R.id.knop3);
		knopholder4 = (LinearLayout) findViewById(R.id.knop4);
		knopcontainer = (RelativeLayout) findViewById(R.id.knopcontainer);
		
		
	

		final VerticalSeekBar vSeekBar = (VerticalSeekBar) findViewById(R.id.SeekBar01);
		vSeekBar.setMax(100);
		
		Drawable img2 = getBaseContext().getResources().getDrawable(
				R.drawable.seek_thumb_normal);
//		img2 = getBaseContext().getResources().getDrawable(
//				R.drawable.seek_thumb_normal);
		img2.setBounds(new Rect(0,
				(int) ((getHeight()-getTitleBarHeight()-img2.getIntrinsicHeight()) * 68 / 100), img2.getIntrinsicWidth(),
				img2.getIntrinsicHeight() + (int) ((getHeight()-getTitleBarHeight()-img2.getIntrinsicHeight()) * 68 / 100)));
		vSeekBar.setThumb(img2);
		
		vSeekBar.setThumbOffset(0);
		vSeekBar.setProgress(24);

		
		// vProgressBar.setSecondaryProgress(200);
		FloorNr = 0;

		// Check progres and set floornumber, set thumb for seekbar,play sound
		// on stoptouch
		vSeekBar.setOnSeekBarChangeListener(new VerticalSeekBar.OnSeekBarChangeListener() {
			int progres;

			@Override
			public void onStopTrackingTouch(VerticalSeekBar seekBar) {
				try {
					MediaPlayer mp = MediaPlayer.create(ScreeningActivity.this,
							R.raw.bell);
					if (mp != null) {
						mp.start();
					}
					mp.setOnCompletionListener(mCompletionListener);
				} catch (Exception e) {
					Log.d("error", e.getMessage());
				}
				if (progres == 0) {
					progres = 3;
				}
				seekBar.setProgress(progres);
				Drawable img2 = getBaseContext().getResources().getDrawable(
						R.drawable.seek_thumb_normal3);
				int IntrinsicWidth = img2.getIntrinsicWidth();
				int IntrinsicHeight = img2.getIntrinsicHeight();
				if (progres >= 73) {
					FloorNr = 3;
					vSeekBar.setProgress(100);
					img2 = getBaseContext().getResources().getDrawable(
							R.drawable.seek_thumb_normal3);
					
					img2.setBounds(new Rect(0, 0, IntrinsicWidth,
							IntrinsicHeight));
					vSeekBar.setThumb(img2);
					vSeekBar.setThumbOffset(0);

				} else if (progres >= 72) {
					FloorNr = 2;
					img2 = getBaseContext().getResources().getDrawable(
							R.drawable.seek_thumb_normal2);
					img2.setBounds(new Rect(0,
							(int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 18 / 100), IntrinsicWidth,
							IntrinsicHeight + (int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 18 / 100)));
					vSeekBar.setThumb(img2);
					vSeekBar.setThumbOffset(0);

				} else if (progres >= 48) {
					FloorNr = 1;
					img2 = getBaseContext().getResources().getDrawable(
							R.drawable.seek_thumb_normal1);
					img2.setBounds(new Rect(0,
							(int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 43 / 100), IntrinsicWidth,
							IntrinsicHeight + (int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 43 / 100)));
					vSeekBar.setThumb(img2);
					vSeekBar.setThumbOffset(0);

				} else if (progres >= 24) {
					FloorNr = 0;
					img2 = getBaseContext().getResources().getDrawable(
							R.drawable.seek_thumb_normal);
					img2.setBounds(new Rect(0,
							(int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 68 / 100), IntrinsicWidth,
							IntrinsicHeight + (int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 68 / 100)));
					vSeekBar.setThumb(img2);
					vSeekBar.setThumbOffset(0);

				} else {
					FloorNr = -1;
					img2 = getBaseContext().getResources().getDrawable(
							R.drawable.seek_thumb_normalb);
					
					img2.setBounds(new Rect(0,
							(int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 93 / 100), IntrinsicWidth,
							IntrinsicHeight + (int) ((getHeight()-getTitleBarHeight()-IntrinsicHeight) * 93 / 100)));
					vSeekBar.setThumb(img2);
					vSeekBar.setThumbOffset(0);
				}

				// empty all relativelayout (buttonholder House)
				knopholder1.removeAllViews();
				knopholder2.removeAllViews();
				knopholder3.removeAllViews();
				knopholder4.removeAllViews();

				ArrayList<CustomRoomButton> tempList = new ArrayList<CustomRoomButton>();

				// get all rooms, put them in temp arraylist, fill
				// screeningrooms
				for (CustomRoomButton temp : screeningRooms) {
					// if (temp.getFloorNumber() == FloorNr) {
					tempList.add(new CustomRoomButton(ScreeningActivity.this,
							temp.getRoomTypeId(), temp.getScreeningRoomId(),
							temp.getReferenceNumber(), temp.getName(), temp
									.getFloorNumber()));
					// }
				}
				screeningRooms = new ArrayList<CustomRoomButton>(tempList);

				SetRooms();

			}

			// release audio
			private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
				public void onCompletion(MediaPlayer mp) {
					mp.release();
				}
			};

			// handle changes in seekbar
			@Override
			public void onStartTrackingTouch(VerticalSeekBar seekBar) {

			}

			int stepSize = 24;

			@Override
			public void onProgressChanged(VerticalSeekBar seekBar,
					int progress, boolean fromUser) {

				int aant = progress % stepSize;
				Log.w("steppen" + aant, "steppen");
				if (progress % stepSize < (stepSize / 2)) {

					progres = ((int) Math.round(progress / stepSize))
							* stepSize;
				} else {
					progres = (((int) Math.round(progress / stepSize)) * stepSize)
							+ stepSize;
				}

			}

		});

		// make layoutparams for knopcontainer
		final RelativeLayout.LayoutParams knopcont = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		knopcont.leftMargin = getWidth() * 18 / 100;
		knopcont.rightMargin = getWidth() * 18 / 100;
		knopcont.topMargin = getWidth() * 22 / 100;
		knopcont.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		knopcontainer.setLayoutParams(knopcont);

		// make layoutparams for Buttons in listview
		final RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		// Add your rules
		rel_btn.addRule(RelativeLayout.CENTER_VERTICAL);
		rel_btn.addRule(RelativeLayout.CENTER_HORIZONTAL);

		// And anything extra
		rel_btn.height = buttonHeight;
		rel_btn.width = buttonWidth;

		// get all roomtypes and put them in arraylist
		List<RoomType> rooms = new ArrayList<RoomType>();
		DBAdapterScreening db = new DBAdapterScreening(this);
		db.open();
		Cursor c = db.getAllRoomTypes();
		while (c.moveToNext()) {
			RoomType rt = new RoomType();
			rt.setId(c.getInt(0));
			rt.setName(c.getString(1));
			rooms.add(rt);
		}
		db.close();

		// add buttons in listview
		for (RoomType rt : rooms) {

			// Create a new RelativeLayout for your RelativeLayout.LayoutParams
			RelativeLayout relativeLayout = new RelativeLayout(
					ScreeningActivity.this);

			// Give your RelativeLayout LayoutParams
			relativeLayout.setLayoutParams(rel_btn);

			Button btnScroll = new CustomRoomButton(this);

			btnScroll.setText(rt.getName());
			btnScroll.setId(rt.getId());
			((CustomRoomButton) btnScroll).setRoomTypeId(rt.getId());
			((CustomRoomButton) btnScroll).setName(rt.getName());

			Drawable img = getBaseContext().getResources().getDrawable(
					R.drawable.geslotendeur);
			img.setBounds(0, 0, 60, 60);
			btnScroll.setCompoundDrawables(null, img, null, null);

			btnScroll.setBackgroundResource(R.drawable.note3);
			btnScroll.setTextSize(TypedValue.COMPLEX_UNIT_PX,
					getWidth() * 6 / 400);
			btnScroll.setTextColor(0xffffffff);
			tf.isBold();
			btnScroll.setTypeface(tf);
			btnScroll.setLayoutParams(rel_btn);

			btnScroll.setPadding(4, 15, 4, 0);
			btnScroll.setWidth(buttonWidth);
			btnScroll.setHeight(buttonHeight);

			btnScroll.setOnLongClickListener(sourceButtonsLongClickListener);

			relativeLayout.addView(btnScroll);
			viewLinksScrol.addView(relativeLayout);

		}

		db.open();
		c = db.getAllScreeningRooms(ScreeningId);

		while (c.moveToNext()) {
			CustomRoomButton btnTag = new CustomRoomButton(this);
			btnTag.setScreeningRoomId(c.getInt(0));
			btnTag.setName(c.getString(4));
			btnTag.setReferenceNumber(c.getInt(5));
			btnTag.setRoomTypeId(c.getInt(2));
			btnTag.setFloorNumber(c.getInt(6));
			screeningRooms.add(btnTag);
		}
		db.close();

		SetRooms();

		delete.setOnDragListener(myDragEventListener);
		delete.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				counter += 1;
				Log.i(TAG, "COUNTER " + counter);
				if (counter == 10) {
					Intent easter = new Intent(ScreeningActivity.this,
							EasterEggActivity.class);
					startActivity(easter);
				}
			}
		});
		viewRechts.setOnDragListener(myDragEventListener);

	}
	
	
	public int getStatusBarHeight() {
	  	Rect r = new Rect();
	  	Window w = getWindow();
	  	w.getDecorView().getWindowVisibleDisplayFrame(r);
	  	return r.top;
	  }

	  public int getTitleBarHeight() {
	  	int viewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
	  	return (viewTop - getStatusBarHeight());
	  }
	  
//	  private Drawable resize(Drawable image) {
//		    Bitmap d = ((BitmapDrawable)image).getBitmap();
//		    Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, 70, 50, false);
//		    return new BitmapDrawable(bitmapOrig);
//		}

	// knoppen rechts zetten

	public void SetRooms() {
		buttonCount = 1;
		counter = 0;
		for (final CustomRoomButton btnHouse : screeningRooms) {
			if (btnHouse.getFloorNumber() == FloorNr) {
				RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				layoutParams.height = buttonHeight;
				layoutParams.width = buttonWidth;

				RelativeLayout relativeLayoutt = new RelativeLayout(
						ScreeningActivity.this);

				relativeLayoutt.setLayoutParams(layoutParams);

				btnHouse.setRoomTypeId(btnHouse.getRoomTypeId());
				btnHouse.setScreeningRoomId(btnHouse.getScreeningRoomId());
				btnHouse.setReferenceNumber(btnHouse.getReferenceNumber());
				btnHouse.setName(((CustomRoomButton) btnHouse).getName());
				btnHouse.setFloorNumber(FloorNr);
				btnHouse.setText(btnHouse.getName());
				Drawable img = getBaseContext().getResources().getDrawable(
						R.drawable.opendeur);
				img.setBounds(0, 0, 50, 50);
				btnHouse.setCompoundDrawables(null, img, null, null);

				btnHouse.setBackgroundResource(R.drawable.note3);
				btnHouse.setTextSize(TypedValue.COMPLEX_UNIT_PX,
						getWidth() * 6 / 400);
				btnHouse.setWidth(buttonWidth);
				btnHouse.setHeight(buttonHeight);
				btnHouse.setId(btnHouse.getScreeningRoomId() + 100);
				btnHouse.setTextColor(0xffffffff);
				Typeface tf = Typeface.createFromAsset(getAssets(), "com.ttf");
				btnHouse.setTypeface(tf);
				btnHouse.setPadding(7, 10, 7, 10);
				btnHouse.setOnLongClickListener(sourceButtonsLongClickListener);
				
				btnHouse.setOnClickListener(roomButtonClicklistener);

				relativeLayoutt.addView(btnHouse, layoutParams);
				if (buttonCount <= 4) {
					knopholder1.addView(relativeLayoutt);
				} else {
					if (buttonCount <= 8) {
						knopholder2.addView(relativeLayoutt);
					} else {
						if (buttonCount <= 12) {
							knopholder3.addView(relativeLayoutt);
						} else
							knopholder4.addView(relativeLayoutt);

					}

				}

				buttonCount += 1;

			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_screening, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.help_btn:
//			Intent intent = getIntent();
//	        String action = intent.getAction();
//	        String type = intent.getType();
			Intent i = new Intent(this, PopupHelpActivity.class);
			i.putExtra("screening",ScreeningId);
			startActivity(i);
			//finish();
			Log.w(TAG,"intent geladen");
			//return true;
			break;
		case R.id.menu_comment:

			// create a fragment manager to show the comment fragment
			FragmentManager fm = getSupportFragmentManager();
			final CommentFragment editCommentDialog = new CommentFragment();

			DBAdapterScreening db = new DBAdapterScreening(this);
			db.open();
			Cursor c = db.getComment(ScreeningId, CommentFragment.SCREENING);
			c.moveToFirst();
			String content = c.getString(0);
			editCommentDialog.setContent(content == null ? "" : content);
			db.close();

			editCommentDialog.mButtonCallback = new CommentFragment.Callbacks() {

				@Override
				public void onCanceled(String comment) {

					// save the changes to the database
					DBAdapterScreening db = new DBAdapterScreening(
							ScreeningActivity.this);
					db.open();
					db.updateComment(ScreeningId, CommentFragment.SCREENING,
							comment);
					db.close();

					// close the dialog
					editCommentDialog.dismiss();

				}
			};
			editCommentDialog.show(fm, "fragment_comment");
		}
		return super.onOptionsItemSelected(item);
	}

	Button.OnLongClickListener sourceButtonsLongClickListener = new Button.OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {

			ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());

			String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
			ClipData dragData = new ClipData((CharSequence) v.getTag(),
					clipDescription, item);

			// http://stackoverflow.com/questions/8875702/android-canvas-locking-throws-illegalargumentexception
			DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
			v.startDrag(dragData, shadowBuilder, v, 0);
			v.setVisibility(View.VISIBLE);
			System.gc();

			return true;
		}
	};

	Button.OnClickListener sourceButtonsClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());

			String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
			ClipData dragData = new ClipData((CharSequence) v.getTag(),
					clipDescription, item);

			// http://stackoverflow.com/questions/8875702/android-canvas-locking-throws-illegalargumentexception
			DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
			v.startDrag(dragData, shadowBuilder, v, 0);
			v.setVisibility(View.VISIBLE);
			System.gc();

		}
	};
	
	OnClickListener roomButtonClicklistener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			Intent roomAct = new Intent(ScreeningActivity.this,
					ScreeningRoomActivity.class);
			roomAct.putExtra("ScreeningRoomId",
					((CustomRoomButton)v).getScreeningRoomId());
			roomAct.putExtra("ScreeningId", ScreeningId);
			ScreeningActivity.this.startActivity(roomAct);
			ScreeningActivity.this.finish();

		}
	};

	protected class MyDragEventListener implements View.OnDragListener {

		@Override
		public boolean onDrag(View v, DragEvent event) {
			final int action = event.getAction();
			// Retrieve the source view using getLocalState()
			final View dragView = (View) event.getLocalState();
			int baseID = dragView.getId();
			switch (action) {
			case DragEvent.ACTION_DRAG_STARTED:
				// All involved view accept ACTION_DRAG_STARTED for
				// MIMETYPE_TEXT_PLAIN

			case DragEvent.ACTION_DRAG_ENTERED:
				if (v == delete & baseID >= 100) {
					delete.setBackgroundResource(R.drawable.trashopen);
				}
				if (baseID < 100) {
					viewRechts.setBackgroundResource(R.drawable.homeselected);
				}

				return true;
			case DragEvent.ACTION_DRAG_LOCATION:

				return true;
			case DragEvent.ACTION_DRAG_EXITED:
				if (v == delete & baseID >= 100) {
					delete.setBackgroundResource(R.drawable.trashclose);
				}
				viewRechts.setBackgroundResource(R.drawable.home);

				return true;
			case DragEvent.ACTION_DROP:
				counter = 0;
				if (v == viewRechts & baseID < 100) {

					RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
					layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
					layoutParams.height = buttonHeight;
					layoutParams.width = buttonWidth;

					RelativeLayout relativeLayoutt = new RelativeLayout(
							ScreeningActivity.this);

					// Give your RelativeLayout LayoutParams
					relativeLayoutt.setLayoutParams(layoutParams);

					btnTag = new CustomRoomButton(ScreeningActivity.this);
					btnTag.setRoomTypeId(((CustomRoomButton) dragView)
							.getRoomTypeId());
					int tempRefNumber = 1;
					for (CustomRoomButton screeningRoom : screeningRooms) {
						if (screeningRoom.getRoomTypeId() == btnTag
								.getRoomTypeId()) {
							Log.i(TAG,
									"RefNumberDROP: "
											+ screeningRoom
													.getReferenceNumber());
							tempRefNumber = 1 + screeningRoom
									.getReferenceNumber();

						}
					}
					btnTag.setReferenceNumber(tempRefNumber);
					btnTag.setName(((CustomRoomButton) dragView).getName()
							+ " " + btnTag.getReferenceNumber());
					btnTag.setFloorNumber(FloorNr);
					DBAdapterScreening db = new DBAdapterScreening(
							ScreeningActivity.this);
					db.open();
					int screeningRoomId = (int) db.insertScreeningRoom(
							ScreeningId,
							((CustomRoomButton) dragView).getRoomTypeId(),
							btnTag.getName(), btnTag.getReferenceNumber(),
							btnTag.getFloorNumber());
					db.close();

					btnTag.setScreeningRoomId(screeningRoomId);

					screeningRooms.add(btnTag);
					
					InsertScreeningItemsTask mInsertItemsTask = new InsertScreeningItemsTask();
					mInsertItemsTask.execute(new Integer[] {
							btnTag.getRoomTypeId(), screeningRoomId, screeningRooms.size()-1 });

					Typeface tf = Typeface.createFromAsset(getAssets(),
							"com.ttf");
					btnTag.setTypeface(tf);
					btnTag.setPadding(7, 10, 7, 10);

					btnTag.setId(baseID + 100);
					btnTag.setText(btnTag.getName());

					Drawable img = getBaseContext().getResources().getDrawable(
							R.drawable.opendeur);
					img.setBounds(0, 0, 50, 50);
					btnTag.setCompoundDrawables(null, img, null, null);

					btnTag.setBackgroundResource(R.drawable.note3);
					btnTag.setTextSize(TypedValue.COMPLEX_UNIT_PX,
							getWidth() * 6 / 400);
					btnTag.setTextColor(0xffffffff);

					btnTag.setOnLongClickListener(sourceButtonsLongClickListener);

					relativeLayoutt.addView(btnTag, layoutParams);

					if (buttonCount <= 4) {
						knopholder1.addView(relativeLayoutt);
					} else {
						if (buttonCount <= 8) {
							knopholder2.addView(relativeLayoutt);
						} else {
							if (buttonCount <= 12) {
								knopholder3.addView(relativeLayoutt);
							} else
								knopholder4.addView(relativeLayoutt);

						}

					}
					buttonCount += 1;
				}

				if (v == delete & baseID >= 100) {
					delete.setBackgroundResource(R.drawable.trashopen);
					
					new AlertDialog.Builder(ScreeningActivity.this)
					.setTitle(
							"Wilt u " + ((CustomRoomButton) dragView).getName()
									+ " verwijderen?")
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {
									// delete screeningroom
									

									screeningRooms.remove(dragView);
									DBAdapterScreening db = new DBAdapterScreening(
											ScreeningActivity.this);
									db.open();
									db.deleteScreeningRoom(((CustomRoomButton) dragView)
											.getScreeningRoomId());
									db.close();

									knopholder1.removeAllViews();
									knopholder2.removeAllViews();
									knopholder3.removeAllViews();
									knopholder4.removeAllViews();

									ArrayList<CustomRoomButton> tempList = new ArrayList<CustomRoomButton>();
									for (CustomRoomButton temp : screeningRooms) {
										// if (temp.getFloorNumber() == FloorNr) {
										tempList.add(new CustomRoomButton(
												ScreeningActivity.this, temp.getRoomTypeId(),
												temp.getScreeningRoomId(), temp
														.getReferenceNumber(), temp.getName(),
												temp.getFloorNumber()));
										// }
									}

									screeningRooms = new ArrayList<CustomRoomButton>(tempList);

									SetRooms();
									

								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int id) {
									// User cancelled the dialog

								}
							}).show();
				}

				// default: // unknown case

				for (CustomRoomButton btnTemp : screeningRooms) {
					// ((RelativeLayout)btnTemp.getParent()).r
				}

			}
			delete.setBackgroundResource(R.drawable.trashclose);
			viewRechts.setBackgroundResource(R.drawable.home);
			return true;
		}
	}

	@SuppressWarnings("deprecation")
	public void getScreenDimensions() {
		Display display = getWindowManager().getDefaultDisplay();

		width = display.getWidth(); // deprecated
		height = display.getHeight(); // deprecated
		Log.i(TAG, "hogteeeeeee" + height);

		/*
		 * Display display = getWindowManager().getDefaultDisplay(); Point size
		 * = new Point(); display.getSize(size); width = size.x; height =
		 * size.y;
		 */
	}

	/**
	 * Represents an asynchronous task to insert screeningitems
	 */
	public class InsertScreeningItemsTask extends
			AsyncTask<Integer, Void, Boolean> {

		private static final String TAG = "InsertScreeningItemsTask";

		@Override
		protected Boolean doInBackground(Integer... values) {
			// TODO: insert screeningitem

			DBAdapterScreening db = new DBAdapterScreening(
					ScreeningActivity.this);
			db.open();
			Cursor c = db.getAllRoomItems(values[0]);
			while (c.moveToNext()) {
				db.insertScreeningItem(values[1], c.getInt(0));
			}
			db.close();
			
			// set the clicklistener after update the database to prevent crashing
			((CustomRoomButton)screeningRooms.get(values[2])).setOnClickListener(roomButtonClicklistener);
			
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			
		}
	}

}
